package com.fjwt.gz.task.notify;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.entity.AwardCouponNotifyEntity;
import com.fjwt.gz.interfaces.ChannelCouponWriteService;
import com.fjwt.gz.service.impl.AwardCouponNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 根据卡券核销回调记录，更新数据库卡券状态信息
 */

@Slf4j
@Component
public class AwardCouponNotifyTask {

    @Autowired
    private AwardCouponNotifyService awardCouponNotifyService;

    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

//    @Scheduled(cron = "${cron.AwardCouponNotifyTask}")//每3秒执行一次
    @Transactional
    public void start() {
        log.info("开始进入：根据卡券核销回调记录，更新数据库卡券状态信息的定时任务，开始时间:{}", DateUtil.now());

        // 当前时间 减去7天
        Date offsetDate = DateUtil.offsetDay(new Date(), -7);

        //查询条件： 同步状态：1未同步的记录 & 回调信息里的卡券状态0：已核销 & 大于创建时间 & 查询7天内的申请单
        LambdaQueryWrapper<AwardCouponNotifyEntity> lambdaQueryWrapper = AwardCouponNotifyEntity.gw();
        lambdaQueryWrapper.eq(AwardCouponNotifyEntity::getState, 1);//未同步的记录
        lambdaQueryWrapper.eq(AwardCouponNotifyEntity::getNotifyState, 0);//回调信息里的卡券状态0：已核销
        lambdaQueryWrapper.ge(AwardCouponNotifyEntity::getCreatedAt, offsetDate);//大于创建时间

        int currentPageIndex = 1; //当前页码
        while (true) {

            try {
                IPage<AwardCouponNotifyEntity> awardCouponNotifyEntityIPage = awardCouponNotifyService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), lambdaQueryWrapper);
                log.info("查询页数：{}，size:{}，结果list：{}", currentPageIndex, QUERY_PAGE_SIZE, JSONUtil.toJsonStr(awardCouponNotifyEntityIPage));
                if (awardCouponNotifyEntityIPage == null || awardCouponNotifyEntityIPage.getRecords().isEmpty()) { //本次查询无结果, 不再继续查询;
                    break;
                }
                for (AwardCouponNotifyEntity awardCouponNotifyEntity : awardCouponNotifyEntityIPage.getRecords()) {
                    log.info("此时进行处理的信息的是：{}", JSONUtil.toJsonStr(awardCouponNotifyEntity));
                    //查询回调处理接口是否存在
                    ChannelCouponWriteService channelCouponWriteService = SpringBeansUtil.getBean(awardCouponNotifyEntity.getIfcode() + "CouponWriteService", ChannelCouponWriteService.class);

                    // 支付通道接口实现不存在
                    if (channelCouponWriteService == null) {
                        log.info("卡券核销处理,接口不存在");
                        continue;
                    }
                    //通过通道类型进行处理逻辑
                    channelCouponWriteService.couponDoNotice(awardCouponNotifyEntity);
                }
                //已经到达页码最大量，无需再次查询
                if (awardCouponNotifyEntityIPage.getPages() <= currentPageIndex) {
                    break;
                }
                currentPageIndex++;
            } catch (BizException e) { //出现异常，直接退出，避免死循环。
                log.error("error", e.getMessage());
                break;
            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }
        }
        log.info("结束任务：根据卡券核销回调记录，更新数据库卡券状态信息的定时任务，结束时间:{}", DateUtil.now());
    }
}
